/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "connection_msg.h"
#include "dialog.h"
#include <QtNetwork>
#include <QTextEdit>
#include <QFileDialog>

#include <QListWidget>
#include <QLineEdit>
#ifdef win32
#include "qt_windows.h"
#endif



#ifndef WIN32 // or something like that...
#define __stdcall
#endif

//////////////////////////////////////////////////////////////////////////
/// \brief CxConnection_msg::CxConnection_msg
CxConnection_msg::CxConnection_msg(Dialog *pdialog):CxConnection(pdialog)
{

}
CxConnection_msg::CxConnection_msg(QTcpSocket *parent,Dialog *pdialog,int icos):CxConnection(parent, pdialog, icos)
{
}
CxConnection_msg::CxConnection_msg(Dialog *pdialog,QTcpSocket *parent):CxConnection(pdialog,parent)
{
}
CxConnection_msg::CxConnection_msg(QTcpSocket *parent,Dialog *pdialog,int icos,int itemp):CxConnection(parent,pdialog,icos,itemp)
{
}



CxConnection_msg::~CxConnection_msg()
{
}



void CxConnection_msg::processRead()
{
    if ( CxConnection::getstate() == P2Pconnection)
    {
        QByteArray data = CxConnection::ioread(CxConnection::iobytesAvailable());
        if(CxConnection::getattachconnect())
            CxConnection::overconnect();
		else
           CxConnection::getattachconnect()->iowrite(data);
		return;
	}
    if (CxConnection::getstate() == WaitingForGreeting)
    { 
        if (!CxConnection::readProtocolHeader())
        {
            CxConnection::ShowLog("user wrong conneting");
            CxConnection::overconnect();
            return;
        }
        if ( CxConnection::getdatetype() != Greeting)
		{
            CxConnection::ioabort();
            CxConnection::ShowLog("not valid user connecting");
            CxConnection::overconnect();
            return;
        }
        CxConnection::setstate(CxConnection::ReadingGreeting);
    }

    if (CxConnection::getstate() == CxConnection::ReadingGreeting)
    {
        if (!CxConnection::hasEnoughData())
            return;

        CxConnection::setconnectbuf(CxConnection::Eread(CxConnection::getbytesfordatenum()));
        if (CxConnection::getconnectbuf().size() != CxConnection::getbytesfordatenum())
        { 
            return;
        }

        CxConnection::setgreetingusername(CxConnection::getio_peer_address_string() + ':'+ QString::number(CxConnection::iopeerport()));
        CxConnection::ShowLog(tr("Greet:")+CxConnection::getgreetingusername());

        CxConnection::setdatetype(CxConnection::Undefined);
        CxConnection::setbytesfordatenum(0);

        
        if (!CxConnection::iovalid())
		{
            CxConnection::ShowLog("no valid connect");
            CxConnection::ioabort();
            return;
        }

        if(0==IScors())//client
		{
            CxConnection::sendIPKEY();
            if(CxConnection::getloguse())
                CxConnection::relogin();
        }
        else
        {//server   
            CxConnection::ShowLog(tr("User:")+QString(CxConnection::getconnectbuf()));
            CxConnection::SetUser(QString(CxConnection::getconnectbuf()).remove(' '));
        }
        CxConnection::getconnectbuf().clear();
        CxConnection::LoginUSER(this);//set user name in client Greet
               
        CxConnection::setstate(CxConnection::ReadyForUse);

        emit CxConnection::readyForUse();
    }
    if (CxConnection::getstate() == CxConnection::ReadyForUse)
    {
        do {
            if (CxConnection::getdatetype() == CxConnection::Undefined)
            {
                if (!CxConnection::readProtocolHeader())
                {
                    //m_icontinuefail = m_icontinuefail + 1;
                    //if(m_icontinuefail>3)
                    //{
                    //	m_icontinuefail = 0;
                    //    CxConnection::ShowLog("wrong connet ");
                    //    CxConnection::overconnect();
                    //}

                    //CxConnection::ShowLog("wrong connet ");
                    //CxConnection::overconnect();
                    return;
                }
            }
            if (!CxConnection::hasEnoughData())
                return;
            CxConnection::processData();
        } while (CxConnection::iobytesAvailable());//m_psocket->bytesAvailable() > 0);

    }
}

void CxConnection_msg::processData()
{
    CxConnection::setconnectbuf( CxConnection::Eread(CxConnection::getbytesfordatenum()));
    if (CxConnection::getconnectbuf().size() != CxConnection::getbytesfordatenum())
    {	
        CxConnection::ShowLog("data loss");
        return;
    }

	QString message;

    switch (CxConnection::getdatetype())
    {
    case Login:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        CxConnection::removelnull(CxConnection::getconnectbuf());
        message = QString::fromUtf8(CxConnection::getconnectbuf()) ;
        CxConnection:setgreetingusername(message.remove(" "));
        CxConnection::IsAdminist(CxConnection::getgreetingusername());

        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
		break;
    case PlainText:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();

        message = QString::fromUtf8(CxConnection::getconnectbuf()) ;
        emit newMessage(CxConnection::getgreetingusername(), message);
        if (!(CxConnection::getgreetingusername().isEmpty() || message.isEmpty()))
			ShowLog(tr("MSG:")+message);
        if(message.mid(0,6)=="value_")
         {
            QString qstrname = message.mid(6);
            QStringList	mslist = qstrname.split("_");

            QString varname = mslist[0];
            QString varvalue = mslist[1];
            getdialog()->SetTextEditText(varname);
            getdialog()->SetValueEditText(varvalue);
            getdialog()->SetValue();
        }
        else if(message.mid(0,8)=="compile ")
        {
            QString astr = message.mid(8);
            getdialog()->SetCodeText(astr);
            getdialog()->TestParserX();
        }
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
        break;
    case Ping:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        CxConnection::sendPong();
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
        break;
    case Pong:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
    
        break;
    case CxCommand:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        CxConnection::removelnull(CxConnection::getconnectbuf());
        message = QString::fromUtf8(CxConnection::getconnectbuf()) ;
        CxConnection::CommandProcess(message);
        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
		break;

	case Logok:
        CxConnection::getpingtimer().stop();
        CxConnection::getpongtime().restart();
        CxConnection::LoginOK();

        CxConnection::getpingtimer().start(PingInterval,this);
        CxConnection::getpongtime().restart();
		break;
    default:
        break;
    }
    CxConnection::setdatetype(CxConnection::Undefined);
    CxConnection::setbytesfordatenum(0);
    CxConnection::getconnectbuf().clear();

}
